import datetime
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from .ser import AddressSer, OrderSer, OrderDetaSer, ScoreSer, SerShoes, SerCate, TypeSer, UserSer, LikeSer, SearchSer, CartSer
from .models import Address, OrderDeta, Order, Shoes, Score, User, Cate, Cart, Type, Like
import re
from utils.mess import send_message
from utils.myredis import MyRedis
from utils.myjwt import jwttoken
from utils.ali import AliPaySDK
import random
import json
from django_filters.rest_framework import FilterSet
import django_filters
from rest_framework.pagination import PageNumberPagination
from django.db.models import Q, F
from drf_haystack.viewsets import HaystackViewSet
from drf_haystack.filters import HaystackFilter
# from.es_utils import get_elasticsearch_client
# Create your views here.


# 注册
class UserView(APIView):
    def post(self, request):
        # 输入用户传递的账号和密码
        userlist = {}
        username = request.data.get('username')
        account = request.data.get('account')
        password = request.data.get('password')
        # 判断用户是否输入
        if account == '' or password == '':
            return Response({'msg': '账号或密码不能为空'})
        if re.match(r'^1[3-9]\d{9}$', account):
            userlist['phone'] = account
        elif re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', account):
            userlist['email'] = account
        userlist['username'] = username
        userlist['password'] = password
        ser = UserSer(data=userlist)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'msg': '注册成功', 'data': ser.data})
        else:
            return Response({'code': 201, 'msg': '注册失败', 'data': ser.errors})

    def put(self, request):
        account = request.data.get('account')
        password = request.data.get('password')
        if re.match(r'^1[3-9]\d{9}$', account):
            data = User.objects.filter(phone=account).first()
        elif re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', account):
            data = User.objects.filter(email=account).first()
        else:
            data = User.objects.filter(username=account).first()
        if data:
            data.password = str(password)
            data.save()
            return Response({'code': 200, 'msg': '修改成功', 'password': password})
        else:
            return Response({'code': 201, 'msg': '修改失败'})

    def get(self, request):
        user = request.query_params.get('user')
        data = User.objects.filter(id=user).first()
        ser = UserSer(data)
        if data:
            return Response({'code': 200, 'msg': '查询成功', 'data': ser.data})
        else:
            return Response({'code': 201, 'msg': '查询失败'})


# 密码登录
class LoginView(APIView):
    def post(self, request):
        account = request.data.get('account')
        password = request.data.get('password')
        if account == '' or password == '':
            return Response({'msg': '账号或密码不能为空'})
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.filter(phone=account, password=password)
        elif re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', account):
            user = User.objects.filter(email=account, password=password)
        else:
            user = User.objects.filter(username=account, password=password)
        if user:
            if user[0].password == password:
                token = jwttoken.get_token(user[0].id, user[0].username)
                # print(token)
                return Response({'code': 200, 'msg': '登录成功', 'data': account, 'id': user[0].id, 'token': token})
            else:
                return Response({'code': 201, 'msg': '密码错误'})
        else:
            return Response({'code': 401, 'msg': '账号不存在'})


# 发送短信
class SendView(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        data = User.objects.filter(phone=phone).first()
        if data:
            code = str(random.randint(1000, 9999))
            res = json.loads(send_message(phone, code, 1440))
            if res['statusCode'] == '000000':
                redis_tool = MyRedis()
                redis_tool.set_str(phone, code)
                return Response({'msg': '验证码发送成功', 'code': 200})
            else:
                return Response({'msg': '验证码发送失败', 'code': 201})
        else:
            return Response({'msg': '该手机号未注册', 'code': 401})


# 短信登录
class CodeLoginView(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        code = str(request.data.get('code'))
        user = User.objects.filter(phone=phone).first()
        # print(user)
        if user:
            redis_tool = MyRedis()
            data = redis_tool.get_str(phone)
            if data == str(code):
                token = jwttoken.get_token(phone, phone)
                return Response({'msg': '登录成功', 'code': 200, 'id': user.id, 'token': token})
            else:
                return Response({'msg': '验证码错误', 'code': 201})
        else:
            return Response({'msg': '该手机号未注册', 'code': 401})


class CateView(ListAPIView):
    queryset = Cate.objects.all()
    serializer_class = SerCate

# class Shoesviews2(APIView):
#      def get(self, request):
#         word = request.GET.get('word', '')
#         # print(word)
#         # s=Search(index='haystack').query("multi_match", query=word, fields=['name', 'category'])
#         # ser = SerShoes(s, many=True)
#         # # print(ser.data[:3])
#         # return Response({'code': 200, 'msg': '查询成功', 'data': ser.data[:9]})
#         es = get_elasticsearch_client()
#
#         # 定义搜索查询
#         query = {
#           "query": {
#             "fuzzy": {
#               "name": {
#                 "value": word
#               }
#             }
#           }
#         }
#
#         # 执行搜索操作
#         res = es.search(index="shoes", body=query)
#         # print(res)
#
#         # 处理搜索结果
#         results = []
#         for hit in res['hits']['hits']:
#             results.append(hit['_source'])
#         return Response({'code': 200, 'msg': '查询成功', 'data': results})


# 分页
class Page(PageNumberPagination):
    page_size = 3
    page_size_query_param = 'size'
    page_query_param = 'page'


class ShoesView(ListAPIView):
    queryset = Shoes.objects.all()
    serializer_class = SerShoes
    pagination_class = Page

    def get_queryset(self):
        query = Q()
        name = self.request.query_params.get('name')
        cate = self.request.query_params.get('cate')
        ca = self.request.query_params.get('ca')
        price = self.request.query_params.get('price')
        if name:
            query &= Q(name=name)
        if cate:
            query &= Q(cate=cate)
        if price:
            query &= Q(price=price)
        if ca:
            query &= Q(cate__name=ca)
        return Shoes.objects.filter(query)


class ShoesView2(ModelViewSet):
    queryset = Shoes.objects.all()
    serializer_class = SerShoes


class Shoe(APIView):
    def get(self, request):
        shoes = Shoes.objects.all()
        ser = SerShoes(shoes, many=True)
        # print(ser.data[:3])
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data[:9]})


class Shoe2(APIView):
    def get(self, request):
        shoes = Shoes.objects.all()
        ser = SerShoes(shoes, many=True)
        # print(ser.data[:3])
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data[:5]})


class ShoeSearch(HaystackViewSet):
    index_models = [Shoes]
    serializer_class = SearchSer
    # filter_backends = [HaystackFilter]

    # def list(self, request):
    #     word = request.query_params.get('text')
    #     if word:
    #         key = 'hot_word'
    #         redis_tool = MyRedis()
    #         redis_tool.set_score(key, word)
    #     return super().list(request.data)


class HotWordViews(APIView):
    def get(self, request):
        key = 'hot_word'
        redis_tool = MyRedis()
        data = redis_tool.get_set(key, 4)
        return Response({'msg': '获取成功', 'data': data})


# 购物车功能  增删改查
class CartView(APIView):
    def post(self, request):
        user = request.data.get('user')
        shoes = request.data.get('shoes')
        cart = Cart.objects.filter(user=user, shoes=shoes).first()
        if cart:
            cart.count += 1
            cart.save()
            return Response({'msg': '商品已存在，数量加一', 'code': 200, 'count': cart.count})
        else:
            ser = CartSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'msg': '添加成功', 'code': 200, 'data': ser.data})
            return Response({'msg': '添加失败', 'code': 201, 'data': ser.errors})

    def get(self, request):
        user = request.query_params.get('user')
        cart = Cart.objects.filter(user=user)
        score = Score.objects.filter(user=user).first()
        # print(score.score)
        totals = 0
        ser = CartSer(cart, many=True)
        for i in ser.data:
            total = int(i['count']) * int(i['shoe']['price'])
            totals += total
            if score.score is not None:
                a = (score.score * 0.1)
        totals1 = totals - a
        return Response({'msg': '查询成功', 'code': 200, 'data': ser.data, 'total': totals,
                         'score': (score.score * 0.1), 'totals': totals1})

    def put(self, request):
        user = request.data.get('user')
        shoes = request.data.get('shoes')
        count = request.data.get('count')
        cart = Cart.objects.filter(user=user, shoes=shoes).first()
        if cart:
            cart.count = count
            cart.save()
            return Response({'msg': '修改成功', 'code': 200, 'data': cart.count})
        else:
            return Response({'msg': '修改失败', 'code': 201})

    def delete(self, request):
        id = request.query_params.get('id')
        if id:
            Cart.objects.filter(id=id).delete()
            return Response({'msg': '删除成功', 'code': 200})
        return Response({'msg': '删除失败', 'code': 201})


# 收藏功能  增删查
class LikeView(APIView):
    def post(self, request):
        user = request.data.get('user')
        shoes = request.data.get('shoes')
        # print(user, shoes)
        like = Like.objects.filter(user=user, shoes=shoes).first()
        # print(like)
        if like:
            return Response({'msg': '已收藏', 'code': 201})
        else:
            ser = LikeSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'msg': '收藏成功', 'code': 200, 'data': ser.data})
            return Response({'msg': '收藏失败', 'code': 201, 'data': ser.errors})

    def get(self, request):
        user = request.query_params.get('user')
        like = Like.objects.filter(user=user)
        ser = LikeSer(like, many=True)
        return Response({'msg': '查询成功', 'code': 200, 'data': ser.data})
    #

    def delete(self, request):
        id = request.query_params.get('id')
        if id:
            Like.objects.filter(id=id).delete()
            return Response({'msg': '删除成功', 'code': 200})
        return Response({'msg': '删除失败，商品不存在', 'code': 201})


# 地址功能  增查
class AddressView(APIView):
    def post(self, request):
        ser = AddressSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '添加成功', 'code': 200, 'data': ser.data})
        return Response({'msg': '添加失败', 'code': 201, 'data': ser.errors})

    def get(self, request):
        user = request.query_params.get('user')
        address = Address.objects.filter(user=user)
        ser = AddressSer(address, many=True)
        return Response({'msg': '查询成功', 'code': 200, 'data': ser.data})


# 地址详情  修改
class Detail(ModelViewSet):
    queryset = Address.objects.all()
    serializer_class = AddressSer

    def put(self, request):
        id = request.data.get('id')
        address = Address.objects.filter(id=id).first()
        if address:
            ser = AddressSer(address, data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'msg': '修改成功', 'code': 200, 'data': ser.data})
            return Response({'msg': '修改失败', 'code': 201, 'data': ser.errors})
        else:
            return Response({'msg': '数据不存在', 'code': 201})


class TypeView(ModelViewSet):
    queryset = Type.objects.all()
    serializer_class = TypeSer


# 生成订单号
def order_num():
    now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    return 'L' + now + '-' + str(random.randint(1000, 9999))


# 订单功能
class OrderView(APIView):
    def post(self, request):
        user = request.data.get('user')
        types = request.data.get('type')
        score = request.data.get('score')

        shoes = Cart.objects.filter(user=user)
        user_score = Score.objects.filter(user=user).first()
        # print(shoes)

        total = 0
        payprice = 0
        for i in shoes:
            # print(i)
            total += int(i.shoes.price) * int(i.count)
        if score:
            if user_score is None:
                return Response({'msg': '用户积分信息不存在', 'code': 400}, status=400)
            payprice = total - (user_score.score * 0.1)
        else:
            payprice = total
        # pay_price = payprice

        obj = {
            'order_id': order_num(),
            'pay_total': total,
            'pay_money': payprice,
            'user': user,
            'type': types,
            'score': score,
        }

        orderser = OrderSer(data=obj)
        if orderser.is_valid():
            orderser.save()

        for j in shoes:
            # print(j)
            obj1 = {
                'order': orderser.data['id'],
                'shoes_id': j.shoes.id,
                'shoes_img': j.shoes.image,
                'shoes_name': j.shoes.name,
                'shoes_price': j.shoes.price,
            }
            # print(obj1)
            orderdeta = OrderDetaSer(data=obj1)
            if orderdeta.is_valid():
                orderdeta.save()

        shoes.delete()
        Score.objects.filter(user=user).update(score=user_score.score-int(score))
        return Response({'msg': '下单成功', 'code': 200, 'data': obj})


class OrderListView(APIView):
    def get(self, request):
        user = request.query_params.get('user')
        order = Order.objects.filter(user=user)
        ser = OrderSer(order, many=True)
        return Response({'msg': '查询成功', 'code': 200, 'data': ser.data})


class OrderDetailView(APIView):
    def get(self, request):
        order = request.query_params.get('order')
        order = OrderDeta.objects.filter(order_id=order).first()
        ser = OrderDetaSer(order)
        return Response({'msg': '查询成功', 'code': 200, 'data': ser.data})


class GetLink(APIView):
    def post(self, request):
        order = request.data.get('order')
        orders = Order.objects.filter(order_id=order, pay_status=1).first()
        if not orders:
            return Response({'msg': '订单不存在', 'code': 201})
        alipay = AliPaySDK()
        link = alipay.page_pay(order, orders.pay_total, '支付')
        return Response({'link': link})


# class SuccessView(APIView):
#     def post(self, request):
#         data = request.data
#         ali = AliPaySDK()
#         success = ali.check_sign(data)
#
#         if success:
#             order = Order.objects.filter(order_id=data['out_trade_no']).first()
#             order.pay_status = 2
#             order.pay_time = data['timestamp']
#             order.pay_num = data['trade_no']
#             order.save()
#             shoes = OrderDeta.objects.filter(order=order.id)
#             serdeta = OrderDetaSer(shoes, many=True)
#             return Response({'msg': '支付成功', 'code': 200, 'data': serdeta.data})
#         return Response({'msg': '支付失败', 'code': 201})

class SuccessView(APIView):
    def post(self, request):
        data = request.data
        print("接收到的支付结果数据:", data)  # 打印数据内容进行调试
        ali = AliPaySDK()
        try:
            success = ali.check_sign(data)
        except KeyError as e:
            print(f"签名验证出错，错误信息: {e}")
            return Response({'msg': '支付结果数据缺少签名信息', 'code': 400})

        if success:
            order = Order.objects.filter(order_id=data['out_trade_no']).first()
            order.pay_status = 2
            order.pay_time = data['timestamp']
            order.pay_num = data['trade_no']
            order.save()
            shoes = OrderDeta.objects.filter(order=order.id)
            serdeta = OrderDetaSer(shoes, many=True)
            return Response({'msg': '支付成功', 'code': 200, 'data': serdeta.data})
        return Response({'msg': '支付失败', 'code': 201})


class UpdateUser(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSer

    def put(self, request):
        user = request.query_params.get('user')
        username = request.data.get('username')
        phone = request.data.get('phone')
        email = request.data.get('email')
        user = User.objects.filter(id=user).first()
        if user:
            user.username = username
            user.phone = phone
            user.email = email
            user.save()
            # ser = UserSer(user)
            return Response({'msg': '修改成功', 'code': 200})
        return Response({'msg': '修改失败', 'code': 201, 'data': '用户不存在'})


